/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package test;

import controller.PerfilJpaController;
import controller.TblusuarioperfilJpaController;
import controller.UsuarioJpaController;
import java.text.DateFormat;
import java.util.List;
import java.util.Locale;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import modelo.Perfil;
import modelo.Tblusuarioperfil;
import modelo.Usuario;

/**
 *
 * @author Cesar
 */
public class frmInsertarUsuarioPerfil extends javax.swing.JFrame {

    /**
     * Creates new form frmInsertarUsuarioPerfil
     */
    public frmInsertarUsuarioPerfil() {
        initComponents();
        this.llenarComboUsuarios();
        this.llenarComboPerfil();
        this.llenarTabla(); 
        
        this.btnActualizarEstado.setEnabled(false);        
        this.boxEstado.setEnabled(false);          
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        labelUsuario = new javax.swing.JLabel();
        boxUsuario = new javax.swing.JComboBox();
        jPanel2 = new javax.swing.JPanel();
        labelPerfil = new javax.swing.JLabel();
        boxPerfil = new javax.swing.JComboBox();
        btnInsertar = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtblUsuarioPerfil = new javax.swing.JTable();
        btnActualizarEstado = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        labelEstado = new javax.swing.JLabel();
        boxEstado = new javax.swing.JComboBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        labelUsuario.setFont(new java.awt.Font("Berlin Sans FB", 0, 14)); // NOI18N
        labelUsuario.setText("Usuario");

        boxUsuario.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        boxUsuario.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boxUsuarioActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelUsuario)
                .addGap(18, 18, 18)
                .addComponent(boxUsuario, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(boxUsuario, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addComponent(labelUsuario))
        );

        labelPerfil.setFont(new java.awt.Font("Berlin Sans FB", 0, 14)); // NOI18N
        labelPerfil.setText("Perfil");

        boxPerfil.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelPerfil)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, Short.MAX_VALUE)
                .addComponent(boxPerfil, javax.swing.GroupLayout.PREFERRED_SIZE, 457, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(boxPerfil, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addComponent(labelPerfil))
        );

        btnInsertar.setText("Guardar");
        btnInsertar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnInsertarActionPerformed(evt);
            }
        });

        jButton2.setText("Salir");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jtblUsuarioPerfil.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jtblUsuarioPerfil.setEditingColumn(0);
        jtblUsuarioPerfil.setEditingRow(0);
        jtblUsuarioPerfil.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtblUsuarioPerfilMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtblUsuarioPerfil);

        btnActualizarEstado.setText("Actualizar Estado");
        btnActualizarEstado.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnActualizarEstadoActionPerformed(evt);
            }
        });

        labelEstado.setFont(new java.awt.Font("Berlin Sans FB", 0, 14)); // NOI18N
        labelEstado.setText("Estado");

        boxEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Seleccionar", "Activo", "Inactivo" }));
        boxEstado.setToolTipText("");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(labelEstado)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE)
                .addComponent(boxEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 457, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(boxEstado, javax.swing.GroupLayout.DEFAULT_SIZE, 31, Short.MAX_VALUE)
                .addComponent(labelEstado))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane1)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jButton2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(btnActualizarEstado)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(btnInsertar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(44, 44, 44)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnInsertar, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnActualizarEstado, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        this.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnInsertarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnInsertarActionPerformed
        if(boxUsuario.getSelectedIndex() !=0 && boxPerfil.getSelectedIndex() !=0)
            {                        
        
        try
        {            
         
            boolean insertado = false;
            TblusuarioperfilJpaController ctrlusPer = new TblusuarioperfilJpaController();
            
            UsuarioJpaController ctrlUsuario = new UsuarioJpaController();
            PerfilJpaController ctrlPerfil = new PerfilJpaController();
                    
            Usuario us = ctrlUsuario.obtenerUsuarioPorNombre(boxUsuario.getSelectedItem().toString()).get(0); 
            Perfil per = ctrlPerfil.obtenerPerfilPorNombre(boxPerfil.getSelectedItem().toString()).get(0);
            
            insertado = ctrlusPer.insertarTblusuarioperfil(us, per);
            
            if(insertado != false)
            {
                JOptionPane.showMessageDialog(null, "Insertado correctamente");
                boxUsuario.setSelectedIndex(0);
                boxPerfil.setSelectedIndex(0);
                this.llenarTabla();            
            }
            else
            {
                JOptionPane.showMessageDialog(null, "El usuario "+boxUsuario.getSelectedItem().toString()+" ya contiene el perfil "+boxPerfil.getSelectedItem().toString());
            }                        
            
        }catch(Exception ex)
        {
            System.out.print("el error es "+ ex.getMessage());
        }
        
        }
            else
            {
                JOptionPane.showMessageDialog(null, "Verifique la seleccion en las listas");
            }
        
    }//GEN-LAST:event_btnInsertarActionPerformed

    private void boxUsuarioActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_boxUsuarioActionPerformed
        //this.obtenerIdComboUsuarios(boxUsuario.getSelectedItem().toString());
    }//GEN-LAST:event_boxUsuarioActionPerformed

    private void btnActualizarEstadoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnActualizarEstadoActionPerformed
        
        if(this.boxEstado.getSelectedIndex() !=0)
        {                        
        try
        {
            boolean actualizado = false;
            TblusuarioperfilJpaController ctrlusPer = new TblusuarioperfilJpaController();
            
            UsuarioJpaController ctrlUsuario = new UsuarioJpaController();
            PerfilJpaController ctrlPerfil = new PerfilJpaController();
            
            Usuario us = ctrlUsuario.obtenerUsuarioPorNombre(jtblUsuarioPerfil.getModel().getValueAt(jtblUsuarioPerfil.getSelectedRow(),0).toString()).get(0); 
            Perfil per = ctrlPerfil.obtenerPerfilPorNombre(jtblUsuarioPerfil.getModel().getValueAt(jtblUsuarioPerfil.getSelectedRow(),1).toString()).get(0);
            
            
            Tblusuarioperfil uspe = new Tblusuarioperfil();
            
            uspe.setEstado(boxEstado.getSelectedItem().toString());
            
            
            actualizado = ctrlusPer.actualizarTblusuarioperfil(us, per,uspe);
            
            if(actualizado != false)
            {
                JOptionPane.showMessageDialog(null, "Actualización correcta.");                
                boxEstado.setSelectedIndex(0);  
                
                this.boxEstado.setSelectedIndex(0);
                this.boxEstado.setEnabled(false);
                this.btnActualizarEstado.setEnabled(false);
                
                this.boxUsuario.setEnabled(true);
                this.boxUsuario.setSelectedIndex(0);
                
                this.boxPerfil.setEnabled(true);
                this.boxPerfil.setSelectedIndex(0);
                
                this.btnInsertar.setEnabled(true);
                        
                this.llenarTabla();
            }
            else
            {
                JOptionPane.showMessageDialog(null, "Error al actualizar el estado del usuario: "+boxUsuario.getSelectedItem().toString());            
            }           
        
        }
        catch(Exception ex)
        {
            System.out.print("el error es "+ ex.getMessage());
        }
        }
        else
        {
            JOptionPane.showMessageDialog(null, "Verifique la seleccion en lla lista de Estado");
        }
    }//GEN-LAST:event_btnActualizarEstadoActionPerformed

    private void jtblUsuarioPerfilMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtblUsuarioPerfilMouseClicked
               
       try
        {
            if(this.jtblUsuarioPerfil.getSelectedRow()>=0)
            {            
                this.btnActualizarEstado.setEnabled(true);
                this.boxUsuario.setSelectedItem(jtblUsuarioPerfil.getModel().getValueAt(jtblUsuarioPerfil.getSelectedRow(), 0));
                this.boxPerfil.setSelectedItem(jtblUsuarioPerfil.getModel().getValueAt(jtblUsuarioPerfil.getSelectedRow(), 1));
                this.boxEstado.setSelectedItem(jtblUsuarioPerfil.getModel().getValueAt(jtblUsuarioPerfil.getSelectedRow(), 2));
                
                this.boxEstado.setEnabled(true);                
                
                this.boxUsuario.setEnabled(false);                                
                this.boxPerfil.setEnabled(false);
                this.btnInsertar.setEnabled(false);
                
            }
            else
            {
                this.btnActualizarEstado.setEnabled(false);                
            }                        
        }
        catch(Exception ex)
        {
            System.out.print("el error es "+ ex.getMessage());        
        }
        
        
    }//GEN-LAST:event_jtblUsuarioPerfilMouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmInsertarUsuarioPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmInsertarUsuarioPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmInsertarUsuarioPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmInsertarUsuarioPerfil.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        
        try{
  //  UIManager.setLookAndFeel("com.jtattoo.plaf.aero.AeroLookAndFeel");
    UIManager.setLookAndFeel("com.jtattoo.plaf.mcwin.McWinLookAndFeel");

        }catch(Exception ex){
        }

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmInsertarUsuarioPerfil().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boxEstado;
    private javax.swing.JComboBox boxPerfil;
    private javax.swing.JComboBox boxUsuario;
    private javax.swing.JButton btnActualizarEstado;
    private javax.swing.JButton btnInsertar;
    private javax.swing.JButton jButton2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtblUsuarioPerfil;
    private javax.swing.JLabel labelEstado;
    private javax.swing.JLabel labelPerfil;
    private javax.swing.JLabel labelUsuario;
    // End of variables declaration//GEN-END:variables


    public void llenarComboUsuarios()
    {
        UsuarioJpaController ctrlUsuario = new UsuarioJpaController();
        List<Usuario> listaUsuario = ctrlUsuario.selectComboUsuarios();                      
        DefaultComboBoxModel model = new DefaultComboBoxModel();  
        
        model.addElement("Seleccionar");
        
        for(int i=0; i<listaUsuario.size(); i++)
        {
            model.addElement(listaUsuario.get(i).getNombreUsuario());                                                           
        }                                              
        boxUsuario.setModel(model);
    }  
    
    public void llenarComboPerfil()
    {
        PerfilJpaController ctrlPerfil = new PerfilJpaController();
        List<Perfil> listaPerfil = ctrlPerfil.selectComboPerfil();                      
        DefaultComboBoxModel model = new DefaultComboBoxModel();
        model.addElement("Seleccionar");
                        
        for(int i=0; i<listaPerfil.size(); i++)
        {
            model.addElement(listaPerfil.get(i).getDescripcion());                                               
        }                                              
        boxPerfil.setModel(model);
    }          
    
    public void llenarTabla()
    {        
        try
        {
        
            TblusuarioperfilJpaController ctrlTblUsPer = new TblusuarioperfilJpaController();
            

            List<Tblusuarioperfil> listUsPe = ctrlTblUsPer.selectAllTblUsuarioPerfil();

            if(listUsPe.size() !=0)
            {
                DefaultTableModel modelo = new DefaultTableModel();

                modelo.addColumn("Usuario");
                modelo.addColumn("Perfil Asignado");
                modelo.addColumn("Estado");
                modelo.addColumn("Fecha de asignacion");
                
                for(int i=0; i<listUsPe.size(); i++)
                {
                    String[] datos = new String[4];
                    datos[0] = String.valueOf(listUsPe.get(i).getFkUsuario().getNombreUsuario());
                    datos[1] = String.valueOf(listUsPe.get(i).getFkPerfil().getDescripcion());
                    datos[2] = String.valueOf(listUsPe.get(i).getEstado().toString());                       
                    DateFormat df =  DateFormat.getDateInstance(DateFormat.FULL, Locale.getDefault());                    
                    String fechaAsignacion = df.format(listUsPe.get(i).getFechaAsignacion());                                                                                                 
                    datos[3] = String.valueOf(fechaAsignacion); 
                    modelo.addRow(datos);
                }
                jtblUsuarioPerfil.setModel(modelo);
                                
            }
            else
            {
                
                JOptionPane.showMessageDialog(null, "No existe ningun dato en la tabla");
            }
            
        } 
        catch(Exception ex)
        {
            System.out.print("el error es "+ ex.getMessage());
            
        }
    }
}
